import { ref } from "vue";
import { defineStore } from "pinia";
import {
  getConfigOfAPP_API,
  createDefaultConfig_API,
  Login_API,
} from "@/axios/api/user.js";

export const useUserStores = defineStore(
  "sy-user",
  () => {
    const config = ref({
      backImage: "/src/static/images/00.jpg",
      tabBarImage: "/src/static/images/02.jpg",
      randomOrder: 0,
      nickName: "",
      messageList: [],
      messageLookId: 0,
    });
    const userCode = ref("");

    const loginAsyncAction = (_userCode) => {
      return new Promise((rel, rea) => {
        Login_API({
          userCode: _userCode,
        })
          .then((res) => {
            console.log(res);
            if (res.data.statusCode == 0) {
              userCode.value = _userCode;
              config.value = res.data.result;
              rel(res);
            } else {
              rea(res.data.message);
            }
          })
          .catch((res) => {
            console.log(res);
            rea(res);
          });
      });
    };

    const logOffAction = () => {
      userCode.value = "";
      //   config.value = {
      //     backImage: "/src/static/images/00.jpg",
      //     tabBarImage: "/src/static/images/02.jpg",
      //     randomOrder: 0,
      //   };
    };

    const getConfigAction = () => {
      return config.value;
    };

    const UpdateConfigAsyncAction = () => {
      return new Promise((rel, rea) => {
        getConfigOfAPP_API()
          .then((res) => {
            const data = res.data.result;
            config.value = data;
            rel(config.value);
          })
          .catch((res) => {
            console.log(res);
            rea(res);
          });
      });
    };

    const createConfigAsyncAction = () => {
      return new Promise((rel, rea) => {
        createDefaultConfig_API()
          .then((res) => {
            if (res.data.statusCode == 0) {
              config.value = res.data.result;
              rel(config.value);
            } else {
              rea(res);
            }
          })
          .catch((res) => {
            console.log(res);
            rea(res);
          });
      });
    };

    const updateMessageLookIdAction = (id) => {
      if (id > config.value.messageLookId) {
        config.value.messageLookId = id;
      }
    };

    return {
      config,
      userCode,
      loginAsyncAction,
      logOffAction,
      getConfigAction,
      UpdateConfigAsyncAction,
      createConfigAsyncAction,
      updateMessageLookIdAction,
    };
  },
  {
    persist: true,
  }
);
